//
//  BaseViewController.swift
//  douyu22
//
//  Created by 朱军华 on 2023/11/30.
//

import UIKit

open class CN_BaseController: UIViewController,UINavigationControllerDelegate {
    
    
      /// 状态栏模式（黑色和白色, 默认是true: 黑色模式, false: 白色模式）
      public var cn_StatusBarDarkMode: Bool = true {
          didSet {
              setNeedsStatusBarAppearanceUpdate()
          }
      }
      
      /// 状态栏是否隐藏，默认false
      public var cn_StatusBarHidden: Bool = false
      
      /// 状态栏样式，区别于childForStatusBarStyle，该方法可以在控制器中单独使用
      ///
      ///如果我们使用了导航控制器 UINavigationController， 且它的 navigationBar 没有被隐藏，那么会发现即使重写 preferredStatusBarStyle方法，这个方法也不会被调用。因为此时状态栏的样式是根据导航栏的样式来自动变换的。
      ///
      ///
      override open var preferredStatusBarStyle: UIStatusBarStyle {
          return cn_StatusBarDarkMode ? .default : .lightContent
      }
      
      // 状态栏是否隐藏
      public override var prefersStatusBarHidden: Bool  {
          return cn_StatusBarHidden
      }
      
      ///- 状态栏更新动画
      override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
          return .fade
      }
      
      /// 导航栏的高度
      public var cn_navigationBarHeight: CGFloat {
          guard let navController = navigationController else {
              return 0
          }
          
          return navController.navigationBar.frame.height
      }
      
      
    public var cn_backBlock: (() -> (Bool))? = { return true }
      
      public var cn_popStart: Bool = false {
          didSet {
              self.navigationController?.popViewController(animated: true)
          }
      }
      
      
      public var cn_hideNavigationBar: Bool = false {
          didSet {
              self.navigationController?.setNavigationBarHidden(cn_hideNavigationBar, animated: true)

          }
      }
      
      public var cn_backgroundColor: UIColor? = nil {
          didSet {
              self.view.backgroundColor = cn_backgroundColor ?? UIColor.white
          }
      }
      public var cn_hidesNavigationBarHairline: Bool  = false {
          didSet {
              self.hideNavBottomHairline(hide: cn_hidesNavigationBarHairline)
          }
      }
      
      // 隐藏NavigationBar下面的黑线
      public func hideNavBottomHairline(hide: Bool) {
          if (self.navigationController != nil){
              let navigationBarImageView = hairlineImageViewInNavigationBar(view: self.navigationController!.navigationBar)
              navigationBarImageView?.isHidden = hide
          }
          
      }

      private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
          if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
              return (view as! UIImageView)
          }
          
          let subviews = (view.subviews as [UIView])
          for subview: UIView in subviews {
              if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
                  return imageView
              }
          }
          return nil
      }
      
      public var cn_barTintColor: UIColor? {
          didSet {
              if #available(iOS 15.0, *) {
                  let apper = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
                  apper.backgroundColor = cn_barTintColor ?? UIColor.white
                  setNav(appearance: apper)

              } else {
                  self.navigationController?.navigationBar.barTintColor = cn_barTintColor ?? UIColor.white            }
              
          }
      }
      
      public var cn_tintColor: UIColor? {
          didSet {
              self.navigationController?.navigationBar.tintColor = cn_tintColor ?? UIColor.white
          }
      }
      
      public var cn_barTintImage: UIImage? {
          didSet {
             
              if #available(iOS 15.0, *) {
                  let apper = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
                  apper.backgroundImage = cn_barTintImage
                  setNav(appearance: apper)
              } else {
                  self.navigationController?.navigationBar.setBackgroundImage(cn_barTintImage, for: .default)
              }
          }
      }
      public var cn_barTitleColor: UIColor? {
          didSet {
             
              if #available(iOS 15.0, *) {
                  let apper = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
                  //设置导航栏标题字体和颜色
                  let titleAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
                  apper.titleTextAttributes = titleAttributes
                  setNav(appearance: apper)

              } else {
                  self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
              }
          }
      }
      public var cn_barTitleFont: UIFont? {
          didSet {
              
              if #available(iOS 15.0, *) {
                  let apper = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
                  //设置导航栏标题字体和颜色
                  let titleAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
                  apper.titleTextAttributes = titleAttributes
                  setNav(appearance: apper)

              } else {
                self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
              }
          }
      }
      public var cn_barButtonItemTitleColor: UIColor? {
          didSet {
              if #available(iOS 15.0, *) {
                  let buttonAppearance = defaultBackButtonConfig()
                  buttonAppearance.normal.titleTextAttributes = [.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, .font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any]
                  setNav(appearance: defaultAppearanceConfig(backButtonAppearance: buttonAppearance))
              } else {
                  // 设置左右边按钮文字颜色和字体
                  self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
                  self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
                  self.navigationItem.backBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
              }
          }
      }
      public var cn_barButtonItemTitleFont : UIFont? {
          didSet {
              if #available(iOS 15.0, *) {
                  let buttonAppearance = defaultBackButtonConfig()
                  buttonAppearance.normal.titleTextAttributes = [.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, .font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any]
                  setNav(appearance: defaultAppearanceConfig(backButtonAppearance: buttonAppearance))
              } else {
                  // 设置左右边按钮文字颜色和字体
                  self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
                  self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
                  self.navigationItem.backBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: cn_barButtonItemTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barButtonItemTitleFont ?? UIFont.cn_fontSize(ofSize: 14.0, weight: .regular) as Any], for: .normal)
              }
          }
      }
      
      public var cn_backIndicatorImage: UIImage? {
          didSet {
              
              if  (self.navigationController?.viewControllers.count)! > 1 {//white_nav
                  let item =  UIBarButtonItem(image: cn_backIndicatorImage, style: UIBarButtonItem.Style.plain, target: self, action: #selector(backButtoinTapped))
                  self.navigationItem.leftBarButtonItem = item
              }
          }
      }

      @objc func backButtoinTapped() {
          if let canback = cn_backBlock,canback() {
              
              self.navigationController?.popViewController(animated: true)
          }
      }
      
    // 在这里实现你的自定义右滑返回逻辑
        @objc func handleCustomBackGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
            
        let translation = gestureRecognizer.translation(in: view)
         switch gestureRecognizer.state {
            case .began:
                // 手势开始
                break
            case .changed:
                // 手势变化
                // 根据百分比执行一些操作，比如改变视图的透明度或移动位置等
                break
            case .ended:
             if let canBack = cn_backBlock,canBack() {
                 // 手势结束
                 if translation.x / view.bounds.width >= 0.3 {
                     navigationController?.popViewController(animated: true)
                 } else {
                     // 否则，重置视图位置或者执行其他操作
                 }
               }
                break
            default:
                break
            }
        }
    
   
        
   
      
      
      open override func viewDidLoad() {
          super.viewDidLoad()
          print("BaseVC----viewDidLoad")
          self.view.backgroundColor = .white
          navigationController?.delegate = self
          
          // 禁用默认的右滑返回手势
         navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
          // 创建一个新的手势识别器
          let customBackGesture = UIPanGestureRecognizer(target: self, action: #selector(handleCustomBackGesture(_:)))
           // 添加手势识别器到视图中
            view.addGestureRecognizer(customBackGesture)
          
          
          if self.navigationController != nil {
              
              
              self.cn_hidesNavigationBarHairline = true
              // 隐藏导航栏下的黑线
              self.hideNavBottomHairline(hide: cn_hidesNavigationBarHairline)
              // 设置导航栏无蒙版效果（不透明）
              self.navigationController?.navigationBar.isTranslucent = false
              // 隐藏导航栏返回按钮的图片
              if  (self.navigationController?.viewControllers.count)! > 1 {//white_nav
                  let item =  UIBarButtonItem(image: cn_backIndicatorImage, style: UIBarButtonItem.Style.plain, target: self, action: #selector(backButtoinTapped))
                  self.navigationItem.leftBarButtonItem = item
              }
              
              // 设置导航栏背景图片
              self.navigationController?.navigationBar.setBackgroundImage(cn_barTintImage, for: .default)
              // iOS15适配
              if #available(iOS 15.0, *) {
                  let appearance = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
                  setNav(appearance: appearance)
              } else {
                  // 隐藏导航栏底部黑线
                  self.navigationController?.navigationBar.shadowImage = (cn_hidesNavigationBarHairline == true ? (UIImage()):(nil))
                  // 设置导航栏标题文本属性
                  self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
                  // 设置导航栏背景色
                  self.navigationController?.navigationBar.barTintColor = cn_barTintColor ?? UIColor.white
                  // 设置导航栏背景图片
                  self.navigationController?.navigationBar.setBackgroundImage(cn_barTintImage, for: .default)
                  self.navigationController?.navigationBar.tintColor = cn_tintColor ?? UIColor.white
         
              }
          }
          
           
          
      }
      
      // 配置导航栏
      @available(iOS 13.0, *)
      func defaultAppearanceConfig(backButtonAppearance:UIBarButtonItemAppearance) -> UINavigationBarAppearance{
          let appearance = UINavigationBarAppearance.init()
         // 去掉半透明效果
         appearance.backgroundEffect = nil
         //根据不透明的背景配置导航栏的外观。它会将导航栏的背景色设置为不透明，并且将其余的属性（如标题文字、按钮等）调整为适合不透明背景的样式。
         appearance.configureWithOpaqueBackground()
         // 设置导航栏背景色
         appearance.backgroundColor = cn_barTintColor ?? UIColor.white
         //设置背景图片
         appearance.backgroundImage = cn_barTintImage
         // 隐藏导航栏返回按钮的文字
          appearance.backButtonAppearance.normal.titlePositionAdjustment = UIOffset(horizontal: -200, vertical: 0)
          //设置导航栏标题字体和颜色
          let titleAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
          appearance.titleTextAttributes = titleAttributes

         appearance.backButtonAppearance = backButtonAppearance
        
          return appearance
      }
      
      // 配置左右按钮
      @available(iOS 13.0, *)
      func defaultBackButtonConfig() -> UIBarButtonItemAppearance {
          // 修改导航栏返回箭头
          let backButtonAppearance = UIBarButtonItemAppearance()
          // Apply the customized back button appearance
         // 该方法可以设置左右边按钮的文字颜色和图片颜色，但是设置不了字体，(该方法在iOS15上面仍然有效)。需要配合 cn_barButtonItemTitleColor 和 cn_barButtonItemTitleFont 一起使用
          backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.clear] // Set the color of the back arrow
          // 创建导航栏外观
          return backButtonAppearance
      }
      
      @available(iOS 13.0, *)
      func setNav(appearance:UINavigationBarAppearance) {
          self.navigationController?.navigationBar.standardAppearance = appearance
          self.navigationController?.navigationBar.compactAppearance = appearance
          self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
      }
      
      
      
      open override func viewDidLayoutSubviews() {
          super.viewDidLayoutSubviews()
          print("BaseVC----viewDidLayoutSubviews")
         
      }
      
      open  override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
          print("BaseVC----viewWillAppear")
          self.navigationController?.setNavigationBarHidden(cn_hideNavigationBar, animated: true)
          if #available(iOS 15.0, *) {
              let appearance = defaultAppearanceConfig(backButtonAppearance: defaultBackButtonConfig())
              setNav(appearance: appearance)

          } else {
              // 设置导航栏标题文本属性
              self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: cn_barTitleColor ?? UIColor.black, NSAttributedString.Key.font: cn_barTitleFont ?? UIFont.cn_fontSize(ofSize: 15.5, weight: .medium) as Any]
              // 设置导航栏背景色
              self.navigationController?.navigationBar.barTintColor = cn_barTintColor ?? UIColor.white
              // 设置导航栏背景图片
              self.navigationController?.navigationBar.setBackgroundImage(cn_barTintImage, for: .default)
           //    修改导航栏返回箭头
              self.navigationController?.navigationBar.backIndicatorImage = cn_backIndicatorImage
              self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = cn_backIndicatorImage
              self.navigationController?.navigationBar.tintColor = cn_tintColor ?? UIColor.white
          }
         
      }
      
    open override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
      }
      
      open override func viewDidDisappear(_ animated: Bool) {
          self.navigationController?.navigationBar.isHidden = false
          super.viewDidDisappear(animated)
          print("BaseVC----viewDidDisappear")
         
      }
      
}

extension CN_BaseController{
    
    // 实现导航控制器的代理方法
    public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
            print("Will show view controller:", viewController)
     
    }

    public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
            print("Did show view controller:", viewController)

     }
    
}


//extension CN_BaseController {
//    /// CN_BaseController 的 push方式跳转
//    public func cn_pushController(controller: CN_BaseController, hideNavigationBar: Bool, statusBarDarkMode: Bool, animated: Bool = true) {
//        if let navigationController = navigationController {
//            navigationController.pushViewController(controller, animated: animated)
//            setNavigationBarHidden(navigationController, hideNavigationBar)
//            setStatusBarStyle(statusBarDarkMode)
//        }
//    }
//
//    /// UIViewController 的 push方式跳转
//    public func cn_pushController(controller: UIViewController, hideNavigationBar: Bool, statusBarDarkMode: Bool, animated: Bool = true) {
//        if let navigationController = navigationController {
//            
//            navigationController.pushViewController(controller, animated: animated)
//            controller.navigationController?.setNavigationBarHidden(true, animated: false)
//            setStatusBarStyle(statusBarDarkMode)
//            
//        }
//    }
//
//    private func setNavigationBarHidden(_ navigationController: UINavigationController, _ hideNavigationBar: Bool) {
//        navigationController.setNavigationBarHidden(hideNavigationBar, animated: false)
//    }
//
//    private func setStatusBarStyle(_ statusBarDarkMode: Bool) {
////        if statusBarDarkMode {
////            UIApplication.shared.statusBarStyle = .default
////        } else {
////            UIApplication.shared.statusBarStyle = .lightContent
////        }
//    }
//}

        

        
